<?php

declare(strict_types=1);

namespace App\Robot\Crontab;

use App\Common\Interfaces\ProxyIpInterface;
use App\Common\Robot\Robot;
use App\CustHub\Mapper\ChRobotMapper;
use App\CustHub\Model\ChRobot;
use App\CustHub\Service\RobotLoginService;
use Carbon\Carbon;
use Hyperf\Coroutine\Coroutine;
use Hyperf\Coroutine\Parallel;
use function Hyperf\Coroutine\co;
use function Swoole\Coroutine\Http\get;

class RobotCheckLoginCrontab
{
    public function execute(): string
    {
        $list = ChRobot::query()
            ->whereHas('server',function ($query) {
                $query->where('gateway','easyWeWork');
            })->get();
        //设置最大并发数 10
        $parallel = new Parallel(10);
        foreach ($list as $robot){
            if($robot->id == 5){
                continue;
            }
            $parallel->add(function () use ($robot) {
                $this->checkLogin($robot);
            });
        }
        $parallel->wait();
        return 'RobotCheckLoginCrontab successfully';
    }

    private function checkLogin(ChRobot $robot)
    {
        $apiService = make(Robot::class,[$robot->server_id,$robot->uuid])->gateway();
        $robotLoginStatus = container()->get(RobotLoginService::class);
        $rst = $apiService->checkLogin();
        if($rst === false){
            if($robot->login_status == 1){
                $this->login($robot,$apiService,$robotLoginStatus);
            }
            return;
        }
        logger()->info("机器人登录状态".json_encode($rst));
        if($rst['user_online_status'] == 0){
            if($robot->login_status == 1){
                $this->login($robot,$apiService,$robotLoginStatus);
            }
        }elseif ($rst['user_online_status'] == 2) {
            if($robot->login_status == 0){
                $robotLoginStatus->loginSuccess($robot,$robot->uuid);
            }
        }else{
            if($robot->login_status == 1){
                $robotLoginStatus->loginOutNotify($robot);
            }
        }
    }

    private function login($robot,$apiService,$robotLoginStatus)
    {
        //需要重新登录
        $stopResponse = $apiService->stopClient();
        if($stopResponse !== false){
            $proxyUrl = '';
//            if($robot->is_yd){
//                $proxyUrl = container()->get(ProxyIpInterface::class)->getShortProxyIp($robot->pro_code,$robot->city_code);
//            }
            $restoreResponse = $apiService->restoreClient($robot->user_id,'',$proxyUrl);
            if($restoreResponse !== false){
                $robotLoginStatus->loginSuccess($robot,$robot->uuid);
            }
        }
    }
}